from loguru import logger
import threading
from flask import Flask, request, jsonify
import socket
import errno
import os

_default = logger
app = Flask(__name__)

client_socket = None

@app.route('/token')
def get_token():
    return "True", 200

@app.route('/tts', methods=['POST'])
def convert_text_to_speech():
    text = request.json.get('text')
    if not text:
        return jsonify({'error': 'No text provided'}), 400

    # 发送文本到TTS处理端
    print(f"收到了 {text}")
    res = send_text_to_tts(text)
    return res, 200

    #return jsonify({'audio':"asdfasdf"}), 200

def send_text_to_tts(text):
    global client_socket
    if client_socket is None:
        return None
    print("not none not return")
    send(client_socket, text)
    #return text.encode()

     # 接收音频流
    lengthBytes = client_socket.recv(4)
    dataLength = int.from_bytes(lengthBytes, byteorder='little')
    audio_data = b''
    while len(audio_data) < dataLength:
        packet = client_socket.recv(dataLength - len(audio_data))
        if not packet:
            break
        audio_data += packet
    print(f"tcp recv len {len(audio_data)}")
    #print(f"tcp recv {audio_data.decode()}")
    #tts_socket.close()
    return audio_data


def runapp():
    global app
    app.run(host='0.0.0.0', port=30100)

tcptag = False
def send(sock, msg):
    #global client_socket
    print("fa")
    if sock is not None:
        tmp = msg.encode()
        dataLength = len(tmp)
        # 发送包长信息
        lengthBytes = dataLength.to_bytes(4, byteorder='little')

        sock.sendall(lengthBytes)
        # 发送数据
        sock.sendall(tmp)

def recvthd(client_socket, addr):
    global tcptag
    count = 50
    while tcptag:
        count -= 1
        if count < 0:
            count = 50
            send(client_socket, "python send ")
        # 接收包长信息
        try:
            lengthBytes = client_socket.recv(4)
            dataLength = int.from_bytes(lengthBytes, byteorder='little')
            data = b''
            while len(data) < dataLength:
                packet = client_socket.recv(dataLength - len(data))
                if not packet:
                    break
                data += packet
            print("Received:", data.decode())

        except socket.error as e:
            if os.name == 'posix' and e.errno == errno.EWOULDBLOCK:
                time.sleep(0.1)
                continue
            elif os.name == 'nt' and e.errno == errno.WSAEWOULDBLOCK:
                time.sleep(0.1)
                continue
            break

if __name__ == "__main__":
    import time
    t = threading.Thread(target=runapp)
    t.daemon = True
    t.start()
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('0.0.0.0', 30099))
    server.listen(1)
    try:
        while True:
            print("主进程运行中")
            client_socket, addr = server.accept()
            #client_socket.setblocking(False)
            tcptag = True
            #client_thread = threading.Thread(target=recvthd, args=(client_socket, addr))
            #client_thread.start()
            print(f"client connect {addr}")
            #time.sleep(1)
    except KeyboardInterrupt:
        print("stop")
        tcptag = False
        server.close()

